<?php
namespace common\services\upload;

use common\models\Common;
use OSS\OssClient;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
use Yii;
use yii\base\Exception;
use yii\web\UploadedFile;

class AliyunOSS extends Common
{
        #q6lx8nqef.bkt.clouddn.com
    public $_bucket = '';
    private $_accessKeyId = '';
    private $_accessKeySecret = '';
    private $_endPoint = '';
    private $ossClient;


    public function init() {
        parent::init();
        $this->_accessKeyId   = Yii::$app->params['ALIYUN_OSS_ACCESS_KEY_ID'];
        $this->_accessKeySecret   = Yii::$app->params['ALIYUN_OSS_ACCESS_KEY_SECRET'];
        $this->_bucket      = Yii::$app->params['ALIYUN_OSS_BUCKET'];
        $this->_endPoint = Yii::$app->params['ALIYUN_OSS_END_POINT'];
    }

    public function getOBJ() {
        return new OssClient($this->_accessKeyId, $this->_accessKeySecret, $this->_endPoint);
    }

    /**
     *
     * @param string $prefix
     * @param string $field
     * @param string $oldKey
     * @return string
     * @throws \OSS\Core\OssException
     */
    public function uploadFile($prefix = 'default', $field = 'file', $oldKey = '') {
        $fileObject = UploadedFile::getInstanceByName($field);
        $ext = $fileObject->getExtension();
        $ossClient = $this->getOBJ();

        #获取临时文件名
        $fileName = $fileObject->tempName;
        #生成文件名
        $key = md5(time() . rand(10000, 99999));

        //上传到七牛后保存的文件名
        $uploadFileName = $prefix.'/'.$key.'.'.$ext;
        $ossClient->uploadFile($this->_bucket, $uploadFileName, $fileName);
//        $ossClient->putObject($this->_bucket, $uploadFileName, $fileName);

//        //如果存在则先删除
//        if ($oldKey) {
//            $this->deleteOldKey($oldKey);
//        }
        return $uploadFileName;
    }

    /**
     * 上传二进制流文件
     * @param string $prefix
     * @param string $data
     * @return bool
     */
    public function put($prefix = 'default',$data = '') {
        $key = md5(time() . rand(10000, 99999));
        $ext = 'png';
        $ossClient = $this->getOBJ();
        //上传后保存的文件名
        $uploadFileName =  $prefix.'/'.$key.'.'.$ext;
        // 要上传文件的本地路径
        $ossClient->putObject($this->_bucket, $uploadFileName, $data);
        return $uploadFileName;
    }


}
